#include "TransCodes.h"
#include <iostream>
using std::string;

TransCode::TransCode(int tsock) {
    csock = tsock;
    if (csock<0) {
        fprintf(stderr, "socket error!\n");
        exit(-1);
    }
    io.readinitb(csock);
}

TransCode::~TransCode() {
    close(csock);
    csock = -1;
}

void TransCode::Close(void) {
    close(csock);
    csock = -1;
}

void TransCode::Open(int tsock) {
    if (tsock<0) {
        fprintf(stderr, "tsock is error!\n", stderr);
        return;
    }
    csock = tsock;
    io.readinitb(csock);
}

int TransCode::transFile(char* file) {
    int fd = open(file, O_RDONLY);
    if (fd < 0) return -1;
    int len=1024;
    char buf[len+23];
    int n;
    while ( (n = read(fd, buf, len)) > 0 ) {
        printf("read size: %d\n", n);
        buf[n] = '\0';
        printf("%s\n", buf);
        if ( write(csock, buf, n) < 0) return -1;
    }
    close(fd);
    return -1;
}

int TransCode::putLine(char* contex) {
    string s = (string)contex + "\r\n";
    if (writen(csock, (char*)s.c_str(), s.length()) < 0) return -1;
    return 1;
}

string TransCode::getLine(int& flag) {
    string ret;
    char buf[1025];
    char* p = buf;
    flag = false;
    while (io.readnb(p, 1) > 0) {
        flag = true;
        if (*p=='\n') {
            *p='\0';
            --p;
            if (*p=='\r') *p='\0';
            ret += buf;
            break;
        }
        if (p-buf>1023) {
            ++p;
            *p='\0';
            ret += buf;
            p = buf;
            continue;
        }
        ++p;
    }
    return ret;
}

